package code.juc.stopThread.volatiledemo;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 演示使用volatile的局限part2：
 * 线程陷入阻塞时, volatile是无法停止线程的。
 * <p>
 * 解决办法： 使用Interrupt()触发中断, 停止线程.
 */
public class WrongWayVolatileCantStopThreadFixed {

    public static void main(String[] args) throws InterruptedException {
        WrongWayVolatileCantStopThreadFixed body = new WrongWayVolatileCantStopThreadFixed();

        BlockingQueue storage = new ArrayBlockingQueue(10);

        Producer producer = body.new Producer(storage);
        Thread producerThread = new Thread(producer);
        producerThread.start();
        Thread.sleep(1000);

        Consumer consumer = body.new Consumer(storage);
        while (consumer.needMoreNums()) {
            System.out.println("消费: " + storage.take());
        }
        System.out.println("消费者不需要再消费啦!");

        // 让生产者停止生产数据.
        producerThread.interrupt();
    }

    /**
     * 生产者
     */
    class Producer implements Runnable {
        private BlockingQueue storage;

        public Producer(BlockingQueue storage) {
            this.storage = storage;
        }

        @Override
        public void run() {
            int num = 0;
            try {
                while (num < Integer.MAX_VALUE / 2 && !Thread.currentThread().isInterrupted()) {
                    if (num % 100 == 0) {
                        storage.put(num);
                        System.out.println(num + " is mod 100, 且放入到了队列中!");
                    }

                    num++;
                }
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            } finally {
                System.out.println("生产者已经停止运行!");
            }
        }
    }

    /**
     * 消费者
     */
    class Consumer {

        BlockingQueue storage;

        public Consumer(BlockingQueue storage) {
            this.storage = storage;
        }

        public boolean needMoreNums() {
            if (Math.random() > 0.95) {
                return false;
            }

            return true;
        }
    }
}